import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/request")
public class RequestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //这个操作是必要的,显示告诉浏览器,你拿到的数据是html
        resp.setContentType("text/html");
        //调用req的各个方法,把得到的结果汇总到一个字符串中,统一返回到页面上.
        StringBuilder respBody = new StringBuilder();


        //下列内容是在浏览器上按照html的方式来展示的,此时\n在html中并不是换行.
        //而使用<br>标签来表示换行
        respBody.append(req.getProtocol());
        respBody.append("<br>");
        respBody.append(req.getMethod());
        respBody.append("<br>");
        respBody.append(req.getRequestURI());
        respBody.append("<br>");
        respBody.append(req.getQueryString());
        respBody.append("<br>");

        //拼接header
        Enumeration<String> headers = req.getHeaderNames();//枚举
        //迭代器遍历枚举里面的每个部分
        while (headers.hasMoreElements()){
            String header = headers.nextElement();//取回
            respBody.append(header);
            //respBody.append(header + ": " + req.getHeader(header));//header的key和value
            respBody.append("<br>");
        }

        //返回结果
        resp.getWriter().write(respBody.toString());
    }
}
